import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_shop/provider/category_goods.dart';
import 'package:provide/provide.dart';
import '../../../model/category.dart';
import '../../../model/category_goods.dart';
import '../../../provider/child_category.dart';
import '../../../service/api_method.dart';
import 'dart:convert';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class RightCategory extends StatefulWidget {
  RightCategory({Key key}) : super(key: key);

  @override
  _RightCategoryState createState() => _RightCategoryState();
}

class _RightCategoryState extends State<RightCategory> {
  ScrollController scrollController = new ScrollController();

  var categorySubId = '';
  int page = 1;

  _getCategoriesGoodsData(String categorySubId) async {
    var params = {
      'categoryId': Provide.value<ChildCategory>(context).categoryId,
      'categorySubId': categorySubId,
      'page': 1
    };

    await request('getMallGoods', params: params).then((val) {
      CategoryGoods categoryGoods = CategoryGoods.fromJson(json.decode(val));

      if (categoryGoods.data == null) {
        Provide.value<CategoryGoodsProvide>(context).setCategoryGoodsList([]);
      } else {
        // 保存到Provide中
        Provide.value<CategoryGoodsProvide>(context)
            .setCategoryGoodsList(categoryGoods.data);
      }
    });
  }

  reset() {
    // 页面重置为1
    page = 1;
    // 右边的滚动回到顶部
    scrollController.jumpTo(0.0);
  }

  Widget _buildSubCategory(SubCategory subCategory) {
    var isSelect = subCategory.mallSubId == categorySubId;

    return Container(
        padding: EdgeInsets.fromLTRB(5.0, 10.0, 5, 10.0),
        child: InkWell(
          onTap: () {
            reset();
            setState(() {
              categorySubId = subCategory.mallSubId;
            });
            Provide.value<ChildCategory>(context)
                .setCategorySubId(subCategory.mallSubId);
            _getCategoriesGoodsData(subCategory.mallSubId);
          },
          child: Text('${subCategory.mallSubName}',
              style: TextStyle(
                  color: isSelect ? Colors.pinkAccent : Colors.black87)),
        ));
    ;
  }

  Widget _buildSubCategories() {
    return Container(
      width: ScreenUtil().setWidth(570),
      height: ScreenUtil().setWidth(90),
      decoration: BoxDecoration(
          color: Colors.white,
          border:
              Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
      child: Provide<ChildCategory>(builder: (context, child, childCategory) {
        return ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: childCategory.subCategories.length,
            itemBuilder: (context, index) {
              return _buildSubCategory(childCategory.subCategories[index]);
            });
      }),
    );
  }

  Widget _buildCategoryGoodsItem(CategoryGoodsItem goodsItem) {
    return Container(
      width: ScreenUtil().setWidth(570.0),
      decoration: BoxDecoration(
          color: Colors.white,
          border:
              Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
      child: Row(
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(8.0),
            width: ScreenUtil().setWidth(200),
            child: Image.network(goodsItem.image),
          ),
          Container(
            child: Column(
              children: <Widget>[
                Container(
                  width: ScreenUtil().setWidth(370),
                  child: Text(goodsItem.goodsName,
                      style: TextStyle(fontSize: ScreenUtil().setSp(26))),
                ),
                Container(
                    width: ScreenUtil().setWidth(370),
                    margin: EdgeInsets.only(top: 20),
                    child: Row(
                      children: <Widget>[
                        Text('价格：${goodsItem.presentPrice}',
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontSize: ScreenUtil().setSp(26),
                                color: Colors.pinkAccent)),
                        Text(
                          '${goodsItem.oriPrice}',
                          style: TextStyle(
                              fontSize: ScreenUtil().setSp(18),
                              color: Colors.black26,
                              decoration: TextDecoration.lineThrough),
                        ),
                      ],
                    ))
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildCategoryGoodsList() {
    return Expanded(
        child: Container(
      width: ScreenUtil().setWidth(570.0),
      child: Provide<CategoryGoodsProvide>(builder: (context, child, data) {
        if (data.categoryGoodsList.length == 0) {
          return Container(
            alignment: Alignment.topCenter,
            child: Text('暂无数据'),
          );
        }
        return EasyRefresh(
            footer: ClassicalFooter(
                bgColor: Colors.white,
                textColor: Colors.pinkAccent,
                infoColor: Colors.pinkAccent,
                infoText: '加载中...',
                loadingText: '上拉加载',
                noMoreText: ''),
            onLoad: () async {
              _getMoreCategoriesGoodsData();
            },
            child: ListView.builder(
                controller: scrollController,
                itemCount: data.categoryGoodsList.length,
                itemBuilder: (context, index) {
                  return _buildCategoryGoodsItem(data.categoryGoodsList[index]);
                }));
      }),
    ));
  }

  // 加载更多数据
  _getMoreCategoriesGoodsData() async {
    Provide.value<ChildCategory>(context).addPage();

    var categoryId = Provide.value<ChildCategory>(context).categoryId;
    var categorySubId = Provide.value<ChildCategory>(context).categorySubId;

    print('===================');
    print(categoryId);
    print(categorySubId);
    print('===================');

    var params = {
      'categoryId': categoryId,
      'categorySubId': categorySubId,
      'page': Provide.value<ChildCategory>(context).page
    };

    await request('getMallGoods', params: params).then((val) {
      CategoryGoods categoryGoods = CategoryGoods.fromJson(json.decode(val));
      if (categoryGoods.data == null) {
        Provide.value<CategoryGoodsProvide>(context)
            .setMoreCategoryGoodsList([]);
      } else {
        // 保存到Provide中
        Provide.value<CategoryGoodsProvide>(context)
            .setMoreCategoryGoodsList(categoryGoods.data);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[_buildSubCategories(), _buildCategoryGoodsList()],
      ),
    );
  }
}
